package net.wicp.tams.common.others.docker;

import java.net.URI;

import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.messages.ContainerConfig;
import com.spotify.docker.client.messages.ContainerCreation;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.Result;

/**
 * com.spotify工具类
 * 
 * @author andy.zhou
 *
 */
@Slf4j
public class DockerUtilSpotify {
	private static DockerUtilSpotify inst = new DockerUtilSpotify();
	private final DockerClient docker;

	public DockerClient getDocker() {
		return docker;
	}

	private DockerUtilSpotify() {
		String url = Conf.get("common.others.docker.url");
		final int poosize = Integer.parseInt(Conf.get("common.others.docker.poolSize"));
		docker = DefaultDockerClient.builder().uri(URI.create(url)).connectionPoolSize(poosize).build();
	}

	public static DockerUtilSpotify getInst() {
		return DockerUtilSpotify.inst;
	}

	/***
	 * 启动容器
	 * 
	 * @param config
	 * @return
	 */
	public Result startContainer(ContainerConfig config) {
		try {
			ContainerCreation container = docker.createContainer(config);
			docker.startContainer(container.id());
			return Result.getSuc(container.id());
		} catch (Exception e) {
			log.error("启动容器失败", e);
			return Result.getError(e.getMessage());
		}
	}

	public Result startContainer(String imageId, String... params) {
		ContainerConfig config = ContainerConfig.builder().image(imageId).cmd(params).build();
		return startContainer(config);
	}

	public Result pushImage(String imageName) {
		try {
			docker.push(imageName);
			return Result.getSuc();
		} catch (Exception e) {
			log.error("推送容器出错", e);
			return Result.getError(e.getMessage());
		}
	}

}
